package com.dtagri.fjwlw.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import com.dtagri.fjwlw.api.ApiHttpClient;
import com.dtagri.fjwlw.bean.UpdataInfo;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnKeyListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;
import android.view.KeyEvent;
import android.widget.Toast;

/**  
 * @Title: Update.java
 * @Description: (添加描述)
 * @author wangyong
 * @date 2011-4-15 下午04:35:45   
 * @version V1.0  
 */
/**
 * 
 */

public class Update implements Runnable {
	private int timeoutConnection = 30000;
	private int timeoutSocket = 5000;
	private static final String TAG = "Update";
	public static final String UPDATE_FILE_NAME = "dtagri.apk";
	public static final String UPDATE_URL = "http://"+ApiHttpClient.HOST+"/Tjwlw"+"/download/"+UPDATE_FILE_NAME;
	public static final String GET_VERSION_URL = "http://"+ApiHttpClient.HOST+"/Tjwlw/api/appversion_list.action";
	private Context context;
	private Handler handler;
	private UpdataInfo info = new UpdataInfo();
	private ProgressDialog progressDialog=null;
	private String method;
	//	private SharedPreferencesData data;

	public Update(Context context, Handler handler,String num) {
		this.context = context;
		this.handler = handler;
		this.method=num;
		if(context!=null&&(!method.equals("index"))){
			progressDialog = ProgressDialog.show(context, "请稍候", "正在获取版本信息...");
			progressDialog.setOnKeyListener(new OnKeyListener() {

				@Override
				public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
					if (keyCode == KeyEvent.KEYCODE_BACK) {
						if(progressDialog!=null)
							progressDialog.dismiss();
						return true;
					}
					return false;
				}
			});
			progressDialog.setCanceledOnTouchOutside(true);
		}
	}


	@Override
	public void run() {
		try {
			// 从资源文件获取服务器 地址
			info = getVersion();
			//			Log.d("tag","-----net UPDATE_URL -----"+UPDATE_URL);
			//			Log.d("tag","-----net version -----"+info.getVersion()+"");
			//			Log.d("tag","-----current version -----"+getVersionCode()+"");
			System.out.println("本地版本号："+getVersionCode());
			System.out.println("服务器版本号："+info.getVersionNum());
			if (info.getVersionNum()<=getVersionCode()) {
				//				Log.i(TAG, "版本号相同无需升级");
				Message msg = Message.obtain();
				msg.what = UpdateUtil.START_MAIN;
				if(info.getVersionNum()==-1){
					msg.what = UpdateUtil.GET_UNDATAINFO_ERROR;
				}
				if(context!=null&&(!method.equals("index"))){
					Thread.sleep(1000);
					progressDialog.dismiss();
				}
				handler.sendMessage(msg);

			} else {
				//				Log.i(TAG, "版本号不同 ,提示用户升级 ");

				Message msg = Message.obtain();
				msg.what = UpdateUtil.UPDATA_CLIENT;
				Bundle bundle = new Bundle();
				info.setUrl(UPDATE_URL);
				bundle.putSerializable("updatainfo", info);
				msg.setData(bundle);
				if(context!=null&&(!method.equals("index")))
				{progressDialog.dismiss();

				}
				handler.sendMessage(msg);
			}
		} catch (Exception e) {
			// 待处理
			Message msg = Message.obtain();
			msg.what = UpdateUtil.GET_UNDATAINFO_ERROR;
			handler.sendMessage(msg);
			if(context!=null&&(!method.equals("index"))){
				progressDialog.dismiss();
			}
			e.printStackTrace();
		}
	}

	public UpdataInfo getVersion() {
		// HashMap map=new HashMap();
		info.setVersionNum(0);
		ArrayList<NameValuePair> paramspairs = new ArrayList<NameValuePair>();
		//		paramspairs.add(new BasicNameValuePair("type", "1"));
		try {
			JSONArray jsonArray = new JSONArray(this.getResponseByServer(
					GET_VERSION_URL, paramspairs));
			JSONObject jsonObject=new JSONObject(jsonArray.get(0).toString());
			//			Log.d("tag","-----请求服务端版本号 -----"+paramspairs);
			info.setVersionNum(jsonObject.optInt("versionNum"));
			info.setUpdateContent(jsonObject.optString("updateContent"));

		} catch (JSONException e) {
			e.printStackTrace();
			return info;
		}
		return info;
	}

	private String getResponseByServer(String url,
			ArrayList<NameValuePair> paramspairs) {
		// Log.i("getServiceObject","connect.................." );
		HttpParams httpParameters = new BasicHttpParams();// Set the timeout in
		// milliseconds until a
		// connection is established.
		HttpConnectionParams.setConnectionTimeout(httpParameters,
				timeoutConnection);// Set the default socket timeout
		// (SO_TIMEOUT) // in milliseconds which is
		// the timeout for waiting for data.
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
		HttpClient client = new DefaultHttpClient(httpParameters);
		StringBuilder sb = new StringBuilder();
		HttpPost post = new HttpPost(url);
		try {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramspairs,
					"utf-8");
			post.setEntity(entity);
			HttpResponse response = client.execute(post);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));

			for (String s = reader.readLine(); s != null; s = reader.readLine()) {
				sb.append(s); // 读取到sb中
			}
			reader.close();
			reader = null;
		} catch (IOException e) {
		}
		return sb.toString();

	}

	/*
	 * 获取当前程序的版本号
	 */
	private String getVersionName() throws Exception {
		// 获取packagemanager的实例
		PackageManager packageManager = context.getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = packageManager.getPackageInfo(
				context.getPackageName(), 0);
		return packInfo.versionName;
	}

	private Integer getVersionCode() {
		Integer version = 0;
		try {
			version = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}

		return version;
	}

	/*	
	 * 用pull解析器解析服务器返回的xml文件 (xml封装了版本号)

	public static UpdataInfo getUpdataInfo(InputStream is) throws Exception {
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(is, "utf-8");// 设置解析的数据源
		int type = parser.getEventType();
		UpdataInfo info = new UpdataInfo();// 实体
		while (type != XmlPullParser.END_DOCUMENT) {
			switch (type) {
			case XmlPullParser.START_TAG:
				if ("version".equals(parser.getName())) {
					info.setVersion(Integer.parseInt(parser.nextText())); // 获取版本号
				} else if ("url".equals(parser.getName())) {
					info.setUrl(parser.nextText()); // 获取要升级的APK文件
				} else if ("description".equals(parser.getName())) {
					info.setDescription(parser.nextText()); // 获取该文件的信息
				}
				break;
			}
			type = parser.next();
		}
		return info;
	}*/

}
